$(document).ready(function() {
	//initialLrDlg()
	initialSelectOption();
	//initProjectPropInfo();
	
	/*****************	prop module 按钮事件绑定		*****************************/
// btn-propEdit: 编辑详情按钮
	$('#btn-propEdit').on('click',function(){
		hideAndShow(['div-propInfoModule','btn-propEdit'],['div-propInputModule']);
	});

// 绑定 btn-propInputModuleCancle 事件
	$('#btn-propInputModuleCancle').on('click',function(){
		console.log("in prop cancle");
		console.log(projectObj);
		project2InputModule(projectObj);
		hideAndShow(['div-propInputModule'],['div-propInfoModule','btn-propEdit']);
	});

// 绑定 btn-propInputModuleReset 事件
	$('#btn-propInputModuleReset').on('click',function(){
		console.log("in prop reset");
		console.log(projectObj);
		project2InputModule(projectObj);
	});

//绑定propInputModule 保存事件
	$('#btn-propInputModuleSave').on('click',function(){
		console.log($(this).attr('id'));
		$('#form-propInputModule').form('submit', {
			url: contextPath+'/project/detail/update/json',
			ajax:true,
			//dataType:"json",
			onSubmit: function(param){
				var isValid = $(this).form('validate');
				
				console.log(param);
				if (!isValid){
					$.messager.alert('消息','输入不合法');
					return false;// hide progress bar while the form is invalid
				}
				$.messager.progress({
					title : '提示',
					text : '更新中~'
				});
				return true;	// return false will stop the form submission
			},
			onBeforeLoad:function(param){
				//console.log('in onBeforeLoad');
				//console.log('in param');
			},
			success:function(str_json){
				console.log("in submit success.");
				console.log(str_json);
				var json=JSON.parse(str_json);
				if(json.success){
					console.log(json.data);
					//copyObject(resultObj.data,projectObj,propInputArray);
					//projectObj=json.data;
					projectObj=inputModel2ProjectObj();
		    		project2InfoModule(projectObj);

					console.log("update success!");
				}else{
					alert("更新数据失败!");
				}
				$.messager.progress('close');	// hide progress bar while submit successfully
				hideAndShow(['div-propInputModule'],['div-propInfoModule','btn-propEdit']);
			},
			onLoadSuccess:function(data){
				//console.log(data);
			}
		});
	});
});

projectObj={
	    "classByImportance": "一般项目",
	    "classByPhase": "可研,初步",
	    "classByPhaseList": [
	        "可研",
	        "初步"
	    ],
	    "profession": "3G/4G宏站（含配套电源）,宽带接入网",
	    "classByProfessionList": [
	        "3G/4G宏站（含配套电源）",
	        "宽带接入网"
	    ],
	    "contactIds": "",
	    "contactNames": "",
	    "contactPhones": "",
	    "contractAmount": 33.53,
	    "departmentIds": "43",
	    "departmentNames": "华中",
	    "description": "111",
	    "designCode": "14001",
	    "designerIds": "1707",
	    "designerNames": "薛龙来",
	    "designerPhones": "",
	    "id": 2780,
	    "investAmount": 3433.43,
	    "partA": "湖北联通",
	    "projectName": "2014年中国联通湖北WCDMA网扩容工程",
	    "projectSn": "14001",
	    "sn": 1,
	    "year": 2014
	};

	projectObj.description="项目团队共14人，历时4个月，完成全省12地市设计工作。本项目为河南联通省管项目，涉及全省18市，我公司负责其中12地市。规模包括自建机房997个、定制机房495个、租赁机房574个，新增外电引入3157站（含利用模块局外电），新购基站空调1801套、基站消防设施1865套、动力环境监控设备2151套，干节点监控641套；新建地面铁塔1374座、拉线塔47座；增高架727座。设计内容包括包含铁塔、机房、空调、外市电引入等无线网配套。";

// project 对象 赋值给 InfoModule
function project2InfoModule(projectObj){
	//#div-propInfoModule .div-prop-value
	//console.log('project2InfoModule');
	//console.log($('#div-propInfoModule').attr('id'));
	$('#div-propInfoModule .div-prop-value').each(function() {
		//console.log('in each');
		//console.log($(this).attr('id'));
		var idString=$(this).attr('id');
		var fieldName=idString.substring(5,idString.length);
		//console.log(fieldName);
		//console.log(projectObj[fieldName]);
		$(this).html(projectObj[fieldName]);
	});

	if(projectObj.investAmount>0){
		$('#info-investAmount').html(projectObj.investAmount+"万");
	}else{
		$('#info-investAmount').html(null);
	}

	console.log(projectObj.beginDate);

	/*if(projectObj.beginDate){
		var date=new Date(projectObj.beginDate);
		console.log(date);
		console.log(date.toLocaleDateString());
		$('#info-beginDate').html(date.toLocaleDateString());
	}else{
		$('#info-beginDate').html(null);
	}*/
	


	console.log("project2InfoModule finished.");
}

// project 对象 赋值给 inputModule
function project2InputModule(projectObj){
	console.log(projectObj);
	//form-propInputModule
	//projectObj.departmentIds=null;
	var projectNotNull=copyObjectWithNotNullField(projectObj);
	
	$('#form-propInputModule').form('load',projectNotNull);
	//处理 beginDate
	if(projectNotNull.beginDate){
		var str_beginDate=projectNotNull.beginDate;
		var int_beginDate=parseInt(str_beginDate);
		var date_beginDate=new Date(int_beginDate);
		var str_beginDateFmt=date_beginDate.format('yyyy-MM-dd');
		$('#input-beginDateFmt').val(str_beginDateFmt);
		$('#input-beginDate').textbox('setText',str_beginDateFmt);
	}


	/*$('#div-propInputModule .div-prop-input').each(function() {
		var idString=$(this).attr('id');
		var fieldName=idString.substring(5,idString.length);
		$("#idString").text('setValue',projectObj[fieldName]);

		console.log(fieldName);
		console.log(projectObj[fieldName]);
	
		//$(this).html(projectObj[fieldName]);
	});*/


	console.log("project2InputModule finished.");
}

function initProjectPropInfo(){
	var postData=new Object();
	var urlInitProjectProp=contextPath+"/project/detail/3/prop.json";
	$.ajax( {  
	    url:urlInitProjectProp,// 跳转到 action  
	    data:postData,  
	    type:'post',  
	    cache:false,  
	    dataType:'json',  
	    beforeSend:function(XMLHttpRequest ){
	    	console.log("in beforeSend");
	    	$.messager.progress({
				title : '提示',
				text : '正在加载数据~'
			});
	    },
	    success:function(json) {
	    	console.log(json);
	    	if(json.success){
	    		projectObj=json.data;
	    		$.each(projectObj,function(i,val){
	    			console.log(val);
	    			/*if(val==null){
	    				projectObj[i]='';
	    			}*/
	    		});
	    		console.log(projectObj);
		    	
		    	project2InputModule(projectObj);
		    	projectObj=inputModel2ProjectObj();
		    	project2InfoModule(projectObj);

		    	/*var date=new Date();
		    	var num_second=$('#input-beginDate').textbox('getValue');
		    	console.log(num_second);
		    	if(num_second){
		    		date.setTime(num_second);
		    		var str_localeDate=date.toLocaleDateString();
		    		$('#input-beginDate').textbox('setText',str_localeDate);
		    	}*/

	    	}else{
	    		alert("加载数据失败.");
	    	}
	    	//$.messager.progress('close');
	    },
	    error : function(data) { 
	    	 //console.log(data);
	    	 $.messager.progress('close');
	    	 alert("Project_Prop数据加载失败，请于管理员联系:18639551912。");
	     }  
	 });

	console.log("initProjectPropInfo finished.");
	//project2InfoModule(projectObj);
	//project2InputModule(projectObj);
	
}

function inputModel2ProjectObj(){
	var jq_form=$('#form-propInputModule');
	var obj_project=$.serializeObject(jq_form);
	console.log(obj_project);

	return obj_project;
}

//初始化 页面 select option 选项
function initialSelectOption(selectMap){
	console.log("in initialSelectOption.");
	var urlOfProjectSelect=contextPath+"/select/class/project.json";
	var className="project";

	//初始化description
	$('#input-description').textbox({    
		multiline:true,
		height:100,
		value:projectObj.description
	});

	$('#input-designerNames').textbox({
		buttonIcon:'icon-add',
		onClickButton:function (){
			createDesignerLtrdDlg();
		}
	});
	
	$('#input-partAName').textbox({
		buttonIcon:'icon-add',
		onClickButton:function (){
			createPartALtrdSingleDlg();
		}
	});
	
	$('#input-contactNames').textbox({
		buttonIcon:'icon-add',
		onClickButton:function (){
			createContactLtrdDlg();
		}
	});

	$.ajax( {  
	    url:urlOfProjectSelect,// 跳转到 action  
	    type:'post',  
	    cache:false,  
	    dataType:'json',  
	    beforeSend:function(XMLHttpRequest ){
	    	$.messager.progress({
				title : '提示',
				text : '正在加载数据~'
			});
	    },
	    success:function(json) {
	    	console.log(json);

	    	if(json.success){
	    		//projectObj=json.data;

	    		var projectSelectMap=json.data;
	    		console.log(projectSelectMap);

	    		$('#input-profession').combobox({    
				    valueField:'value',    
				    textField:'text',
				    data:projectSelectMap.profession,
				    multiple:true
				    
				});

				$('#input-type').combobox({    
				    valueField:'value',    
				    textField:'text',
				    data:projectSelectMap.type,
				    multiple:false
				    
				});

				$('#input-departmentIds').combobox({    
				    valueField:'value',    
				    textField:'text',
				    data:projectSelectMap.department,
				    multiple:true,
				   /* onSelect:function(record){
				    	$('#input-departmentNames').val($('#input-departmentIds').combobox('getText'));
				    },
				    onUnselect:function(record){
				    	console.log("in unselect");
				    	console.log(record);
				    	$('#input-departmentNames').val($('#input-departmentIds').combobox('getText'));
				    }*/
				});

				initProjectPropInfo();
		    	
	    	}else{
	    		alert("加载数据失败.");
	    	}
	    	$.messager.progress('close');
	    },
	    error : function(data) { 
	    	 //console.log(data);
	    	 $.messager.progress('close');
	    	 alert("Project_Prop数据加载失败，请于管理员联系:18639551912。");
	     }  
	 });

	//input-year
	var now=new Date();
	var yearOption=new Array();
	for(var i=2010;i<now.getFullYear();i++){
		var yearobj=new Object();
		yearobj.value=i;
		yearobj.label=i+"年";
		console.log(yearobj);
		yearOption.push(yearobj);
		
	}
	//console.log(yearOption);
	/*$('#input-year').combobox({    
	    valueField:'value',    
	    textField:'label',
	    data:yearOption
	    
	});  */
	

	$('#input-beginDate').textbox({
				buttonIcon:'icon-add',
				onClickButton:function (){
					console.log('hit beginDate btn');
	
			    	
			    	WdatePicker({
			    		el:'input-beginDateFmt',
			    		//vel:'dateValue',
			    		firstDayOfWeek:1,
			    		readOnly:true,
			    		position:{left:-300,top:0},
			    		//startDate:str_beginDate,
			    		onpicked:function(){
			    			var str_pickedDate=$dp.cal.getDateStr();
			    			console.log(str_pickedDate);
			    			
			    			var date_pickedDate=new Date(str_pickedDate);
			    			console.log(date_pickedDate);
			    			var int_second=date_pickedDate.getTime();
			    			console.log(int_second);
			    			$('#input-beginDate').textbox('setValue',date_pickedDate.getTime());
			    			$('#input-beginDate').textbox('setText',str_pickedDate);
			    		},
			    		oncleared:function(){
			    			$('#input-beginDate').textbox('setValue',null);
			    			$('#input-beginDate').textbox('setText',null);
			    		}
			    	});
				}
			});
	
	console.log("prop end initial");
}



function createDesignerLtrdDlg(){
	var str_idPrefix="designer";
	var str_contentDivId="ltrdDlg";
	var str_dlgTitle="关联设计人员";
	var obj_treeParameter=new Object();

	var idsOfCheckDesigner=$("#input-designerIds").val();

	obj_treeParameter={
		url:contextPath+"/tree/ltrd/departmentWithDesigner",
		queryParams:{'idsOfCheckDesigner':idsOfCheckDesigner}
	};
	
	var obj_datagridParameter=new Object();
	obj_datagridParameter.columns=[[{'field':'id','title':'id','width':'100','hidden':'true'},
						     		{'field':'departmentName','title':'部门','width':'100'},
						     		{'field':'name','title':'姓名','width':'100'}]]; 
	
	var callFun1=function(){
		console.log("callFun1 is running.");
	}
	var array_customFun=new Array();
	/*var customFun1=new Object();
	customFun1.label="add";
	customFun1.func=function(){
		console.log("func1 is running.");
	}
	array_customFun.push(customFun1);*/
	
	var ltrdSelectObject=ltrdSelect(str_contentDivId,str_idPrefix,str_dlgTitle,obj_treeParameter,obj_datagridParameter,setDesignerIdsAndPhones,array_customFun);
}

function createPartALtrdSingleDlg(){
	var str_idPrefix="partA";
	var str_contentDivId="ltrdDlg";
	var str_dlgTitle="关联甲方";
	var obj_treeParameter=new Object();


	var str_checkedId=$("#input-partAId").val();

	console.log(str_checkedId);
	obj_treeParameter={
		url:contextPath+"/tree/ltrdSingle/partA",
		queryParams:{"str_checkedId":str_checkedId}
	};
	
	var obj_datagridParameter=new Object();
	obj_datagridParameter.columns=[[{'field':'id','title':'id','width':'100','hidden':'true'},
						     		{'field':'type','title':'类别','width':'100'},
						     		{'field':'province','title':'省份','width':'100'},
						     		{'field':'name','title':'简称','width':'100'}]]; 
	
	var callFun=setPartAIdAndName;
	var array_customFun=new Array();
	/*var customFun1=new Object();
	customFun1.label="add";
	customFun1.func=function(){
		console.log("func1 is running.");
	}
	array_customFun.push(customFun1);*/
	

	var ltrdSingleSelectObject=ltrdSelectSingle(str_contentDivId,str_idPrefix,str_dlgTitle,obj_treeParameter,obj_datagridParameter,callFun,str_checkedId,array_customFun);
}



// designerLtrdDlg ok回调函数:根据designer Dlg 返回值，设置 DesignerIdsAndPhones
function setDesignerIdsAndPhones(resultArray){
	console.log("in callFunc");
	console.log(resultArray);
	var phoneArray=new Array();
	var idsArray=new Array();
	var nameArray=new Array();
	$.each(resultArray,function(){
		phoneArray.push(this.phone);
		idsArray.push(this.id);
		nameArray.push(this.name)
	});
	console.log(idsArray);
	console.log(phoneArray);
	console.log(nameArray);
	$("#input-designerIds").val(idsArray.join(","));
	$("#input-designerPhones").textbox('setValue',phoneArray.join(","));
	$("#input-designerNames").textbox('setValue',nameArray.join(","));
}

// partALtrdDlg ok回调函数:
function setPartAIdAndName(resultArray){
	console.log("in callFunc");
	console.log(resultArray);
	var partAName;
	var partAId;

	if(resultArray.length==0){
		partAName='';
		partAId='';
	}else{
		partAName=resultArray[0].name;
		partAId=resultArray[0].id;
	}
	console.log(partAName);

	$("#input-partAName").textbox('setValue',partAName);
	$("#input-partAId").val(partAId);
	
}


function createContactLtrdDlg(){
	var str_idPrefix="contact";
	var str_contentDivId="ltrdDlg";
	var str_dlgTitle="关联-联系人";
	var obj_treeParameter=new Object();

	var str_checkedIds=$('#input-contactIds').val();
	var str_partAId=$("#input-partAId").val();

	obj_treeParameter={
		url:contextPath+"/tree/ltrd/contact",
		queryParams:{'checkedIds':str_checkedIds,
					 'partAId':str_partAId	}
		};
	
	var obj_datagridParameter=new Object();
	obj_datagridParameter.columns=[[{'field':'id','title':'id','width':'100','hidden':'true'},
						     		{'field':'partAName','title':'所属单位','width':'100'},
						     		{'field':'name','title':'姓名','width':'100'}]]; 
	
	var callFun=setContactIdsNamesAndPhones;
	var array_customFun=new Array();
	/*var customFun1=new Object();
	customFun1.label="add";
	customFun1.func=function(){
		console.log("func1 is running.");
	}
	array_customFun.push(customFun1);*/
	
	var ltrdSelectObject=ltrdSelect(str_contentDivId,str_idPrefix,str_dlgTitle,obj_treeParameter,obj_datagridParameter,callFun,array_customFun);
}

function setContactIdsNamesAndPhones(resultArray){
	console.log("in setContactIdsNamesAndPhones callFunc");
	console.log(resultArray);
	var phoneArray=new Array();
	var idsArray=new Array();
	var nameArray=new Array();

	$.each(resultArray,function(){
		phoneArray.push(this.phone);
		idsArray.push(this.id);
		nameArray.push(this.name)
	});
	console.log(idsArray);
	console.log(phoneArray);
	console.log(nameArray);
	$("#input-contactIds").val(idsArray.join(","));
	$("#input-contactPhones").textbox('setValue',phoneArray.join(","));
	$("#input-contactNames").textbox('setValue',nameArray.join(","));
}

function copyObjectWithNotNullField(srcObject){
	if((typeof srcObject) =='object'){
		var targetObject=new Object();
		$.each(srcObject,function(i,val){
			//console.log(i+" = "+val);
			if(val != null){
				targetObject[i]=srcObject[i];
			}
		});
		return targetObject;
	}
}


//目前没用上
function createCalendar(){
	$('#calendar').calendar({    
		firstDay:1,
	    current:new Date(),
	    formatter: function(date){
	    	console.log('in formatter');
			return date.getDate();
		},
	    onSelect:function(date){
	    	console.log(date.toLocaleDateString());
	    	$('#input-beginDate').textbox('setValue',date.getTime());
	    	$('#input-beginDate').textbox('setText',date.toLocaleDateString());

	    	/*console.log(date);
	    	console.log(date.toDateString());
	    	console.log(date.getTime());
	    	
	    	console.log(date.toLocaleString());
	    	
	    	console.log(date.toUTCString());
	    	console.log(date.toLocaleTimeString());
	    	console.log(date.toUTCString());*/
	    	$("#calendar").hide();
	    }
	    
	    
	});  
					
	$("#calendar").hide();
}